import React, { useState } from 'react'
import { Row, Col, Table, Card, Tag } from 'antd'
import { useRequest, useMount } from 'ahooks'
import moment from 'moment'

import {
  COMMUNICATION_APPLICATION_STATUS,
  COMMUNICATION_CHAIN_STATUS,
  CROSS_CHAIN_CONTRACT_STATUS,
} from '@/pages/Dashboard/components/CrossChain/enums'
import Title from '@/pages/Dashboard/common/Tilte'

import StatisticsGroup from '@/pages/Dashboard/components/CrossChain/components/StatisticsGroup'
import CustomCard from '@/pages/Dashboard/components/CrossChain/components/CustomCard'
import NewCard from '@/pages/Dashboard/components/CrossChain/components/NewCard'
import { getRelayChainStatistics, listContracts, listCommunicationChains, listApplications } from '@/pages/Dashboard/components/CrossChain/service'
import { checkPermission } from '@/components/AuthComponent/utils'
import AuthComponent from '@/components/AuthComponent'

import './index.less'
import { USER_INFO } from '@/Utils/CONST'

const CrossChain = ({ history }) => {
  const [statistics, setStatistics] = useState([])
  const [contracts, setContracts] = useState([])
  const [communicationChains, setCommunicationChains] = useState([])
  const [applications, setApplications] = useState([])
  const { loading: loadingApplications, run: getApplications } = useRequest(listApplications, { manual: true })
  const userInfo = JSON.parse(localStorage.getItem(USER_INFO) || '{}')
  const voteStatusEnum = Object.freeze({
    applied: '未投票',
    applying: '未投票',
    rejected: '已投票',
    connected: '已投票',
    error: '出错',
  })
  const contractColumns = [
    {
      title: '合约名称',
      key: 'name',
      dataIndex: 'name',
    },
    {
      title: '合约ID',
      key: 'id',
      dataIndex: 'id',
    },
    {
      title: '创建时间',
      key: 'created_at',
      dataIndex: 'created_at',
      render: (v) => v ? moment(v).format('YYYY-MM-DD HH:mm:ss') : '--',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (text) => <Tag color={CROSS_CHAIN_CONTRACT_STATUS[text].status}>{CROSS_CHAIN_CONTRACT_STATUS[text].label}</Tag>,
    },
  ]
  const crossApplicationColumn = [
    {
      title: '申请ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '来源链',
      dataIndex: 'source_name',
      key: 'source',
    },
    {
      title: '目标链',
      dataIndex: 'target_name',
      key: 'target',
    },
    {
      title: '投票状态',
      dataIndex: 'status',
      key: 'status',
      // eslint-disable-next-line react/display-name
      render: (text) => <Tag color={['connected', 'rejected'].indexOf(COMMUNICATION_APPLICATION_STATUS[text].value) >= 0 ? 'success' : 'error'}>{voteStatusEnum[COMMUNICATION_APPLICATION_STATUS[text].value]}</Tag>,
    },
  ]
  const { loading: loadingStatistic, run: loadStatistic } = useRequest(getRelayChainStatistics, { manual: true })
  const { loading: loadingContracts, run: loadContracts } = useRequest(listContracts, { manual: true })
  const { loading: loadingCommunicationChains, run: loadCommunicationChains } = useRequest(listCommunicationChains, { manual: true })
  const queryStatistic = async() => {
    try {
      const res = await loadStatistic()
      const { data: { block_height: blockHeight, communication_chain_count: communicationChainCount,
        contract_count: contractCount, node_count: nodeCount, transaction_count: transactionCount }} = res
      setStatistics([
        {
          label: '区块高度',
          key: 'blockHeight',
          value: blockHeight,
          showDetail: false,
        },
        {
          label: '交易数量',
          key: 'txCount',
          value: transactionCount,
          showDetail: false,
        },
        {
          label: '合约数量',
          key: 'contractNum',
          value: contractCount,
          showDetail: true,
          // detailLink: '/dashboard/cross-chain/blockList',
          detailLink: '/dashboard/cross-chain/contracts',
        },
        {
          label: '节点数量',
          key: 'nodeNum',
          value: 1 || nodeCount, // 目前只有1个节点
          showDetail: false,
        },
        {
          label: '通讯链数量',
          key: 'commChainNum',
          value: communicationChainCount,
          showDetail: false,
        },
      ])
    } catch (e) {
      console.error(e)
    }
  }

  const queryContracts = async() => {
    try {
      const res = await loadContracts({ page: 1, per_page: 3 })
      const { data: { data: contracts }} = res
      setContracts(contracts)
    } catch (e) {
      console.error(e)
    }
  }

  const queryCommunicationChains = async() => {
    try {
      const res = await loadCommunicationChains({ per_page: -1 })
      const { data: { data: chains }} = res
      setCommunicationChains(chains)
      // setContracts(contracts)
    } catch (e) {
      console.error(e)
    }
  }

  const queryApplications = async(params) => {
    try {
      const res = await getApplications(params)
      const { data: { data }} = res
      setApplications(data)
    } catch (e) {
      console.error(e)
    }
  }

  useMount(() => {
    queryStatistic()
    queryContracts()
    queryCommunicationChains()
    queryApplications({
      per_page: 3,
    })
  })

  return (
    <div>
      <Card loading={loadingStatistic} title={<Title title="中继链" />}>
        <StatisticsGroup history={history} statistics={statistics} />
      </Card>
      {
        checkPermission('cross-chain-communication', 'GET') &&
        <Card loading={loadingCommunicationChains} title={<Title title="通讯链" className="title middle-title" />} style={{ marginTop: 24 }}>
          <div className="group">
            {communicationChains.map((chain) => {
              const chainItems = [
                {
                  key: 'contractType',
                  title: '通讯链类型',
                  value: 'Fabric',
                },
                {
                  key: 'org',
                  title: '所属联盟',
                  value: chain.consortium_name || '-',
                },
                {
                  key: 'channel',
                  title: '所属通道',
                  value: chain.channel_name || '-',
                },
                {
                  key: 'id',
                  title: '通讯链ID',
                  value: chain.id,
                },
              ]
              const onClickItem = () => {
                if (COMMUNICATION_CHAIN_STATUS[chain.status].value === 'running') {
                  history.push({
                    pathname: `/dashboard/cross-chain/communicationChain/info/${chain.id}`,
                  })
                }
              }
              return (
                <CustomCard onClick={onClickItem} key={chain.id}
                  className="sub-card"
                  data={chain}
                  title={chain.name}
                  status="SUCCESS"
                  items={chainItems} subTitle={chain.consortium_domain || '-'}
                  hasTag={chain.creator === userInfo.id} tagText="我的" />
              )
            })}
            {
              checkPermission('cross-chain-communication-create', 'POST') &&
            <NewCard onClick={() => history.push({ pathname: '/dashboard/cross-chain/communicationChain/new' })} title="创建通讯链" />
            }
          </div>
        </Card>
      }
      <div style={{ marginTop: 24 }}>
        <Row gutter={24}>
          {
            checkPermission('cross-chain-contracts', 'GET') &&
            <Col span={12}>
              <Card title={<Title title="部署合约" className="title" isMore goMore={() => history.push({ pathname: '/dashboard/cross-chain/contracts' })} />}>
                <Table loading={loadingContracts} dataSource={contracts} columns={contractColumns} pagination={false} rowKey="id" />
              </Card>
            </Col>
          }
          {
            checkPermission('cross-chain-applications', 'GET') &&
            <Col span={12}>
              <Card title={<Title title="跨链申请" className="title" isMore goMore={() => history.push({ pathname: '/dashboard/cross-chain/applications' })} />}>
                <Table loading={loadingApplications} dataSource={applications} columns={crossApplicationColumn} pagination={false} rowKey="id" />
              </Card>
            </Col>
          }
        </Row>
      </div>
    </div>
  )
}

export default AuthComponent('cross-chain')(CrossChain)
